package com.lagou.rpcserver;

import com.lagou.codec.RpcDecoder;
import com.lagou.codec.RpcEncoder;
import com.lagou.codec.impl.JSONSerializer;
import com.lagou.rpcserver.lagou.handler.UserServiceHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class ServerBootstrap {

	public static void main(String[] args) throws InterruptedException {
		final ConfigurableApplicationContext run = SpringApplication.run(ServerBootstrap.class, args);
		final UserServiceHandler handler = run.getBean(UserServiceHandler.class);

		startServer(handler);
	}

	//创建一个方法启动服务器
	public static void startServer(ChannelHandler handler) throws InterruptedException {
		NioEventLoopGroup bossGroup = new NioEventLoopGroup();
		NioEventLoopGroup workGroup = new NioEventLoopGroup();

		io.netty.bootstrap.ServerBootstrap bootstrap = new io.netty.bootstrap.ServerBootstrap();

		bootstrap.group(bossGroup, workGroup)
				.channel(NioServerSocketChannel.class)
				.childHandler(new ChannelInitializer<NioSocketChannel>() {
					protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
						ChannelPipeline pipeline = nioSocketChannel.pipeline();
						pipeline.addFirst(new RpcDecoder(JSONSerializer.getInstance()));
						pipeline.addLast(new RpcEncoder(JSONSerializer.getInstance()));
						pipeline.addLast(handler);
					}
				});
		//4.绑定端口
		bootstrap.bind(8999).sync();
	}

}
